package cn.gp.chatclient.ui.panel;

import cn.gp.chatclient.api.user.req.AddFriendRequest;
import cn.gp.chatclient.model.FriendRequestVo;
import cn.gp.chatclient.model.UserVo;
import cn.gp.chatclient.service.UserService;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.util.List;


/**
 * @ClassName FriendRequestPanel
 * @Description TODO
 * @Author He Guoping
 * @Date 2025/6/17 10:44
 * @Version JDK17
 */
@Slf4j
public class FriendRequestPanel extends JPanel {
    private final UserService userService;
    private final UserVo currentUser;
    private JList<FriendRequestVo> requestList;
    private DefaultListModel<FriendRequestVo> listModel;
    private JTextField searchField;
    private JList<UserVo> searchResultList;
    private DefaultListModel<UserVo> searchResultModel;

    public FriendRequestPanel(UserService userService, UserVo currentUser) {
        this.userService = userService;
        this.currentUser = currentUser;
        initUI();
        loadFriendRequests();
    }

    private void initUI() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建搜索面板
        JPanel searchPanel = new JPanel(new BorderLayout());
        searchField = new JTextField();
        JButton searchButton = new JButton("搜索");
        searchButton.addActionListener(e -> searchUsers());
        searchPanel.add(searchField, BorderLayout.CENTER);
        searchPanel.add(searchButton, BorderLayout.EAST);

        // 创建搜索结果列表
        searchResultModel = new DefaultListModel<>();
        searchResultList = new JList<>(searchResultModel);
        searchResultList.setCellRenderer(new UserListCellRenderer());
        JScrollPane searchScrollPane = new JScrollPane(searchResultList);
        searchScrollPane.setPreferredSize(new Dimension(0, 150));

        // 创建添加好友按钮
        JButton addFriendButton = new JButton("添加好友");
        addFriendButton.addActionListener(e -> showAddFriendDialog());

        // 创建好友请求列表
        listModel = new DefaultListModel<>();
        requestList = new JList<>(listModel);
        requestList.setCellRenderer(new FriendRequestRenderer());
        requestList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane requestScrollPane = new JScrollPane(requestList);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        JButton acceptBtn = new JButton("接受");
        JButton rejectBtn = new JButton("拒绝");
        JButton refreshBtn = new JButton("刷新");

        acceptBtn.addActionListener(e -> handleRequest(1));
        rejectBtn.addActionListener(e -> handleRequest(2));
        refreshBtn.addActionListener(e -> loadFriendRequests());

        buttonPanel.add(acceptBtn);
        buttonPanel.add(rejectBtn);
        buttonPanel.add(refreshBtn);

        // 组装面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(searchPanel, BorderLayout.NORTH);
        topPanel.add(searchScrollPane, BorderLayout.CENTER);
        topPanel.add(addFriendButton, BorderLayout.SOUTH);

        add(topPanel, BorderLayout.NORTH);
        add(requestScrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void searchUsers() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入搜索关键词");
            return;
        }

        userService.searchUsers(keyword)
            .thenAccept(response -> {
                if (response.isSuccess()) {
                    SwingUtilities.invokeLater(() -> {
                        searchResultModel.clear();
                        for (UserVo user : response.getData()) {
                            searchResultModel.addElement(user);
                        }
                    });
                } else {
                    SwingUtilities.invokeLater(() -> 
                        JOptionPane.showMessageDialog(this, 
                            "搜索失败: " + response.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE));
                }
            })
            .exceptionally(throwable -> {
                SwingUtilities.invokeLater(() -> 
                    JOptionPane.showMessageDialog(this, 
                        "搜索失败: " + throwable.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE));
                return null;
            });
    }

    private void showAddFriendDialog() {
        UserVo selectedUser = searchResultList.getSelectedValue();
        if (selectedUser == null) {
            JOptionPane.showMessageDialog(this, "请先选择要添加的用户");
            return;
        }

        String message = JOptionPane.showInputDialog(this, 
            "请输入验证消息", 
            "添加好友", 
            JOptionPane.QUESTION_MESSAGE);

        if (message != null) {
            AddFriendRequest request = new AddFriendRequest();
            request.setReceiverId(selectedUser.getId());
            request.setRequestMessage(message);
            
            userService.sendFriendRequest(request)
                .thenAccept(response -> {
                    if (response.isSuccess()) {
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(this, "好友请求已发送");
                            searchField.setText("");
                            searchResultModel.clear();
                        });
                    } else {
                        SwingUtilities.invokeLater(() -> 
                            JOptionPane.showMessageDialog(this, 
                                "发送好友请求失败: " + response.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE));
                    }
                })
                .exceptionally(throwable -> {
                    SwingUtilities.invokeLater(() -> 
                        JOptionPane.showMessageDialog(this, 
                            "发送好友请求失败: " + throwable.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE));
                    return null;
                });
        }
    }

    private void loadFriendRequests() {
        if (currentUser == null) {
            JOptionPane.showMessageDialog(this, "请先登录");
            return;
        }

        userService.getFriendRequests()
            .thenAccept(response -> {
                if (response.isSuccess()) {
                    SwingUtilities.invokeLater(() -> {
                        listModel.clear();
                        if (response.getData() != null) {
                            for (FriendRequestVo request : response.getData()) {
                                if (request != null) {
                                    listModel.addElement(request);
                                }
                            }
                        }
                    });
                } else {
                    SwingUtilities.invokeLater(() -> 
                        JOptionPane.showMessageDialog(this, 
                            "加载好友请求失败: " + response.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE));
                }
            })
            .exceptionally(throwable -> {
                SwingUtilities.invokeLater(() -> 
                    JOptionPane.showMessageDialog(this, 
                        "加载好友请求失败: " + throwable.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE));
                return null;
            });
    }

    private void handleRequest(int status) {
        FriendRequestVo selected = requestList.getSelectedValue();
        if (selected == null) {
            JOptionPane.showMessageDialog(this, "请先选择好友请求");
            return;
        }

        userService.handleFriendRequest(selected.getId(), status)
            .thenAccept(response -> {
                if (response.isSuccess()) {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, 
                            status == 1 ? "已接受好友请求" : "已拒绝好友请求");
                        loadFriendRequests();
                    });
                } else {
                    SwingUtilities.invokeLater(() -> 
                        JOptionPane.showMessageDialog(this, 
                            "处理好友请求失败: " + response.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE));
                }
            })
            .exceptionally(throwable -> {
                SwingUtilities.invokeLater(() -> 
                    JOptionPane.showMessageDialog(this, 
                        "处理好友请求失败: " + throwable.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE));
                return null;
            });
    }

    public void refreshRequests() {
        if (userService.getCurrentUserId() == null) {
            log.warn("用户未登录，无法刷新好友请求列表");
            return;
        }

        // 从服务器获取最新的好友请求列表
        userService.getFriendRequests().thenAccept(responseVo -> {
            if (responseVo.isSuccess()) {
                List<FriendRequestVo> requests = responseVo.getData();
                SwingUtilities.invokeLater(() -> {
                    listModel.clear();
                    if (requests != null) {
                        for (FriendRequestVo request : requests) {
                            listModel.addElement(request);
                        }
                    }
                });
            } else {
                log.error("获取好友请求列表失败: {}", responseVo.getMessage());
            }
        }).exceptionally(throwable -> {
            log.error("获取好友请求列表异常", throwable);
            return null;
        });
    }

    private static class UserListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                     boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof UserVo) {
                UserVo user = (UserVo) value;
                setText(String.format("%s (%s)", user.getNickname(), user.getUsername()));
                setIcon(new ImageIcon(user.getAvatar()));
            }
            return this;
        }
    }

    private static class FriendRequestRenderer extends JLabel implements ListCellRenderer<FriendRequestVo> {
        public FriendRequestRenderer() {
            setOpaque(true);
            setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        }

        @Override
        public Component getListCellRendererComponent(JList<? extends FriendRequestVo> list,
                                                      FriendRequestVo request,
                                                      int index,
                                                      boolean isSelected,
                                                      boolean cellHasFocus) {
            if (request == null) {
                setText("");
                setIcon(null);
                return this;
            }

            UserVo requester = request.getRequesterInfo();
            if (requester == null) {
                setText("未知用户");
                setIcon(null);
            } else {
                String text = String.format("<html><b>%s</b> (%s)<br>%s</html>",
                        requester.getNickname(),
                        requester.getUsername(),
                        request.getRequestMessage() != null ? request.getRequestMessage() : "");
                setText(text);
                if (requester.getAvatar() != null) {
                    setIcon(new ImageIcon(requester.getAvatar()));
                } else {
                    setIcon(null);
                }
            }

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }

            return this;
        }
    }
}
